package com.cspg.design.presenter;

import android.app.Activity;
import android.content.Intent;
import android.util.Log;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TableRow;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSONObject;
import com.baidu.mapapi.model.LatLng;
import com.baidu.mapapi.utils.DistanceUtil;
import com.cspg.design.CSPGApplication;
import com.cspg.design.MainActivity;
import com.cspg.design.R;
import com.cspg.design.bean.UserInfo;
import com.cspg.design.bean.deviceBean.CrossDeviceBean;
import com.cspg.design.bean.deviceBean.HotLineWorkPlanBean;
import com.cspg.design.bean.deviceBean.PointDeviceBean;
import com.cspg.design.bean.deviceBean.PolylineDeviceBean;
import com.cspg.design.bean.modelLibrary.TowerLibrary;
import com.cspg.design.bean.modelLibrary.TransformerLibrary;
import com.cspg.design.bean.modelLibrary.WireLibrary;
import com.cspg.design.bean.projectBean.ProjectBean;
import com.cspg.design.bean.shemeBean.MyHighVoltageSchemeBean;
import com.cspg.design.bean.shemeBean.MyLowVoltageSchemeBean;
import com.cspg.design.bean.userInfoBean.UserInfoBean;
import com.cspg.design.common.Constant;
import com.cspg.design.dao.gen.CrossDeviceBeanDao;
import com.cspg.design.dao.gen.DaoSession;
import com.cspg.design.dao.gen.HotLineWorkPlanBeanDao;
import com.cspg.design.dao.gen.MyHighVoltageSchemeBeanDao;
import com.cspg.design.dao.gen.MyLowVoltageSchemeBeanDao;
import com.cspg.design.dao.gen.PointDeviceBeanDao;
import com.cspg.design.dao.gen.PolylineDeviceBeanDao;
import com.cspg.design.dao.gen.ProjectBeanDao;
import com.cspg.design.dao.gen.TowerLibraryDao;
import com.cspg.design.dao.gen.TransformerLibraryDao;
import com.cspg.design.dao.gen.WireLibraryDao;
import com.cspg.design.dto.Device;
import com.cspg.design.dto.PointDeviceDto;
import com.cspg.design.dto.PoleLibraryDto;
import com.cspg.design.dto.PolylineDeviceDto;
import com.cspg.design.dto.ProjectDto;
import com.cspg.design.dto.submit.Area;
import com.cspg.design.dto.submit.Cross;
import com.cspg.design.dto.submit.HotLineWork;
import com.cspg.design.dto.submit.Land;
import com.cspg.design.dto.submit.Pile;
import com.cspg.design.dto.submit.ProjectSubmitToReviewDto;
import com.cspg.design.dto.submit.ProjectSubmitToReviewPlatform;
import com.cspg.design.dto.submit.Wire;
import com.cspg.design.model.User;
import com.cspg.design.request.DeviceLibrary;
import com.cspg.design.request.GTask;
import com.cspg.design.request.PointDevice;
import com.cspg.design.ui.gtasks.GTasksActivity;
import com.cspg.design.ui.login.LoginActivity;
import com.cspg.design.ui.project.ProjectTotal;
import com.cspg.design.utils.Utils;
import com.cspg.design.widget.CSPGProgressBar;
import com.cspg.design.widget.ToastUtils;

import org.greenrobot.greendao.rx.RxDao;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.regex.Pattern;

import rx.Scheduler;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;

public class GTaskPresenter implements IPresenter {
    private final GTask gTaskModel;
    private final Activity activity;

    private final DaoSession daoSession;

    private CSPGProgressBar cspgProgressBar;
    private RxDao<UserInfoBean, Long> userInfoBeanLongRxDao;
    private int type;
    private int index;

    private final List<ProjectBean> projectBeanList;
    private final ArrayList<HashMap<String, String>> dataList;
    private final SimpleAdapter adapter;
    private ProjectBean projectBean;
    private final DeviceLibrary deviceLibrary;
    List<PolylineDeviceBean> polylineDeviceBeanList;
    List<PointDeviceBean> pointDeviceBeanList;
    private final String[] crossInfo = {
            "10kV线路、等级公路（10kV线路）",
            "导线跨越 低压电力线路、通信线路（10kV线路）",
            "经济作物、房屋（10kV线路）",
            "导线跨越 跨越河流 导线截面150以内 河宽50m以内（10kV线路）",
            "导线跨越 跨越河流 导线截面300以内 河宽150m以内（10kV线路）",
            "10kV线路、等级公路（380V、220V线路）",
            "导线跨越 低压电力线路、通信线路（380V、220V线路）",
            "经济作物、房屋（380V、220V线路）",
            "导线跨越 跨越河流 导线截面150以内 河宽50m以内（380V、220V线路）",
            "导线跨越 跨越河流 导线截面300以内 河宽150m以内（380V、220V线路）"};

    public GTaskPresenter(Activity activity, ListView listView, List<ProjectBean> projectBeanList, ArrayList<HashMap<String, String>> dataList,
                          SimpleAdapter adapter) {
        this.gTaskModel = new GTask(this);
        this.activity = activity;
        this.daoSession = ((CSPGApplication) activity.getApplication()).getDaoSession();
        this.projectBeanList = projectBeanList;
        this.dataList = dataList;
        this.adapter = adapter;
        deviceLibrary = new DeviceLibrary(daoSession);
        deviceLibrary.requestPoleLibrary();
        deviceLibrary.requestTransformerLibrary();
        deviceLibrary.requestWireLibrary();
    }


    public void updateProject(ProjectBean projectBean, int type, int index) {
        if (cspgProgressBar == null) {
            cspgProgressBar = CSPGProgressBar.show(activity);
        } else {
            cspgProgressBar.show();
        }
        try {
            this.type = type;
            this.index = index;
            this.projectBean = projectBean;
            gTaskModel.updateProject(projectModeConverterFactoryToDto(projectBean));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void uploadDeviceData(int type, List<PointDeviceBean> pointDeviceBeanList,
                                 List<PolylineDeviceBean> polylineDeviceBeanList,
                                 ProjectBean projectBean,
                                 int index) {
        if (cspgProgressBar == null) {
            cspgProgressBar = CSPGProgressBar.show(activity);
        } else {
            cspgProgressBar.show();
        }
        try {
            this.projectBean = projectBean;
            this.polylineDeviceBeanList = polylineDeviceBeanList;
            this.pointDeviceBeanList = pointDeviceBeanList;
            this.index = index;
            this.type = 4;

            Device device = new Device();
            device.setPointDevices(pointDeviceBeansConverterFactoryToDtos(pointDeviceBeanList));
            device.setPolylineDevices(polylineDeviceBeansConverterFactoryToDtos(polylineDeviceBeanList));
            device.setProject(projectModeConverterFactoryToDto(projectBean));
            gTaskModel.uploadAllDevice(device);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void uploadPoints(List<PointDeviceBean> pointDeviceBeanList) {
        if (cspgProgressBar == null) {
            cspgProgressBar = CSPGProgressBar.show(activity);
        } else {
            cspgProgressBar.show();
        }
        try {
            gTaskModel.uploadAllPoint(pointDeviceBeansConverterFactoryToDtos(pointDeviceBeanList));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void getPoints(String projectId) {
        if (cspgProgressBar == null) {
            cspgProgressBar = CSPGProgressBar.show(activity);
        } else {
            cspgProgressBar.show();
        }
        try {
            gTaskModel.getPointDeviceByProjectId(projectId);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void uploadPolylines(List<PolylineDeviceBean> polylineDeviceBeanList) {
        if (cspgProgressBar == null) {
            cspgProgressBar = CSPGProgressBar.show(activity);
        } else {
            cspgProgressBar.show();
        }
        try {
            List<PolylineDeviceDto> list = polylineDeviceBeansConverterFactoryToDtos(polylineDeviceBeanList);
            gTaskModel.uploadAllPolyline(list);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void deleteDevice(String projectId) {
        if (cspgProgressBar == null) {
            cspgProgressBar = CSPGProgressBar.show(activity);
        } else {
            cspgProgressBar.show();
        }
        gTaskModel.deletePointDeviceByProjectId(projectId);
        gTaskModel.deletePolylineDeviceByProjectId(projectId);

    }

    public void submitToReview(ProjectBean projectBean, int type, int index) {
        if (cspgProgressBar == null) {
            cspgProgressBar = CSPGProgressBar.show(activity);
        } else {
            cspgProgressBar.show();
        }
        try {
            this.type = type;
            this.index = index;
            this.projectBean = projectBean;
            String REGEX = "[^(0-9)]";
            ProjectSubmitToReviewPlatform projectSubmitToReviewPlatform = new ProjectSubmitToReviewPlatform();
            projectSubmitToReviewPlatform.setPName(projectBean.getProjectName());
            projectSubmitToReviewPlatform.setPCode(projectBean.getProjectCode());

            HotLineWorkPlanBean hotLineWorkPlanBean = daoSession.getHotLineWorkPlanBeanDao().queryBuilder().where(HotLineWorkPlanBeanDao.Properties.ProjectId.eq(projectBean.getProjectId())).unique();
            HotLineWork hotLineWork = new HotLineWork();
            if (hotLineWorkPlanBean != null) {
                hotLineWork.setN1(hotLineWorkPlanBean.getN1());
                hotLineWork.setN2(hotLineWorkPlanBean.getN2());
                hotLineWork.setN3(hotLineWorkPlanBean.getN3());
                hotLineWork.setN4(hotLineWorkPlanBean.getN4());
                hotLineWork.setN5(hotLineWorkPlanBean.getN5());
                hotLineWork.setN6(hotLineWorkPlanBean.getN6());
                hotLineWork.setN7(hotLineWorkPlanBean.getN7());
                hotLineWork.setN8(hotLineWorkPlanBean.getN8());
                hotLineWork.setN9(hotLineWorkPlanBean.getN9());
                hotLineWork.setN10(hotLineWorkPlanBean.getN10());
                hotLineWork.setN11(hotLineWorkPlanBean.getN11());
                hotLineWork.setN12(hotLineWorkPlanBean.getN12());
            } else {
                hotLineWork.setN1(0);
                hotLineWork.setN2(0);
                hotLineWork.setN3(0);
                hotLineWork.setN4(0);
                hotLineWork.setN5(0);
                hotLineWork.setN6(0);
                hotLineWork.setN7(0);
                hotLineWork.setN8(0);
                hotLineWork.setN9(0);
                hotLineWork.setN10(0);
                hotLineWork.setN11(0);
                hotLineWork.setN12(0);
            }


            projectSubmitToReviewPlatform.setHotLineWork(hotLineWork);

            String investment = projectBean.getProjectInvestment();
            if (investment == null || investment.isEmpty() || investment.equals("0") || investment.equals("null")) {
                Double cost = costInvest(projectBean.getProjectId());
//                projectBean.setProjectInvestment(cost+"");
                investment = cost + "";
            }
            projectSubmitToReviewPlatform.setPInvestment(Float.parseFloat(investment));
            String carDistance = projectBean.getCarDistance();
            if (carDistance == null || carDistance.isEmpty()
            ) {
                carDistance = "0.0";
            }
            String voltageLevel = projectBean.getVoltageLevel();
            if (voltageLevel == null || voltageLevel.isEmpty()) {
                voltageLevel = "0";
            } else {
                voltageLevel = Pattern.compile(REGEX).matcher(voltageLevel).replaceAll("").trim();
            }
            String handDistance = projectBean.getHandDistance();
            if (handDistance == null || handDistance.isEmpty()
            ) {
                handDistance = "0.0";
            }
            if (voltageLevel.trim().isEmpty()) {
                voltageLevel = "0";
            }
            projectSubmitToReviewPlatform.setPVoltage(Integer.parseInt(voltageLevel));
            projectSubmitToReviewPlatform.setCarDistance(Float.parseFloat(carDistance));
            projectSubmitToReviewPlatform.setHumanDistance(Float.parseFloat(handDistance));
            String schemeName = projectBean.getSchemeName();
            String schemeType = projectBean.getSchemaType();
            Area area = new Area();
            Land land = new Land();
            if (schemeName == null || schemeName.isEmpty()) {
                ToastUtils.toast(this.activity, "此设计无方案。。。");
                return;
            }
            if (schemeType.equals("high")) {
                MyHighVoltageSchemeBean myHighVoltageSchemeBean = daoSession.getMyHighVoltageSchemeBeanDao().queryBuilder()
                        .where(MyHighVoltageSchemeBeanDao.Properties.SchemeName.eq(schemeName),
                                MyHighVoltageSchemeBeanDao.Properties.UserName.eq(projectBean.getUserName())).unique();
                if (myHighVoltageSchemeBean == null) {
                    ToastUtils.toast(this.activity, "此设计无方案详细数据。。。");
                } else {
                    area.setJT(Float.parseFloat(myHighVoltageSchemeBean.getHardSoil()));
                    area.setPTT(Float.parseFloat(myHighVoltageSchemeBean.getCommonSoil()));
                    area.setNSK(Float.parseFloat(myHighVoltageSchemeBean.getMudPuddle()));
                    area.setSSS(Float.parseFloat(myHighVoltageSchemeBean.getLooseSandstone()));
                    area.setYSRG(Float.parseFloat(myHighVoltageSchemeBean.getRock()));

                    land.setPD(Float.parseFloat(myHighVoltageSchemeBean.getFlatGround()));
                    land.setQL(Float.parseFloat(myHighVoltageSchemeBean.getHills()));
                    land.setSD(Float.parseFloat(myHighVoltageSchemeBean.getHillyArea()));
                }

            } else if (schemeType.equals("low")) {
                MyLowVoltageSchemeBean myLowVoltageSchemeBean = daoSession.getMyLowVoltageSchemeBeanDao().queryBuilder()
                        .where(MyLowVoltageSchemeBeanDao.Properties.SchemeName.eq(schemeName),
                                MyLowVoltageSchemeBeanDao.Properties.UserName.eq(projectBean.getUserName())).unique();
                if (myLowVoltageSchemeBean == null) {
                    ToastUtils.toast(this.activity, "此设计无方案详细数据。。。");
                } else {
                    area.setJT(Float.parseFloat(myLowVoltageSchemeBean.getHardSoil()));
                    area.setPTT(Float.parseFloat(myLowVoltageSchemeBean.getCommonSoil()));
                    area.setNSK(Float.parseFloat(myLowVoltageSchemeBean.getMudPuddle()));
                    area.setSSS(Float.parseFloat(myLowVoltageSchemeBean.getLooseSandstone()));
                    area.setYSRG(Float.parseFloat(myLowVoltageSchemeBean.getRock()));

                    land.setPD(Float.parseFloat(myLowVoltageSchemeBean.getFlatGround()));
                    land.setQL(Float.parseFloat(myLowVoltageSchemeBean.getHills()));
                    land.setSD(Float.parseFloat(myLowVoltageSchemeBean.getHillyArea()));
                }
            }
            projectSubmitToReviewPlatform.setPArea(area);
            projectSubmitToReviewPlatform.setPLand(land);
            List<Pile> piles = new ArrayList<>();
            List<Wire> wires = new ArrayList<>();
            List<PointDeviceBean> pointDeviceBeans = daoSession.getPointDeviceBeanDao().queryBuilder()
                    .where(PointDeviceBeanDao.Properties.ProjectId.eq(projectBean.getProjectId())).list();
            List<PolylineDeviceBean> polylineDeviceBeans = daoSession.getPolylineDeviceBeanDao().queryBuilder()
                    .where(PolylineDeviceBeanDao.Properties.ProjectId.eq(projectBean.getProjectId())).list();
            for (PointDeviceBean pointDeviceBean : pointDeviceBeans) {


                Pile pile = new Pile();
                pile.setPoleNum(pointDeviceBean.getPointName());
                Double longitude = pointDeviceBean.getLongitude();
                Double latitude = pointDeviceBean.getLatitude();
                pile.setGpsCoordinate(longitude + "," + latitude);
                pile.setPoleCode(pointDeviceBean.getPointModel());
                pile.setPoleState(pointDeviceBean.getPointStatue());
                pile.setPileID(pointDeviceBean.getPointUuid());
                if (pointDeviceBean.getFarImage() != null && !pointDeviceBean.getFarImage().isEmpty()) {
                    String far = Constant.FILEHost + pointDeviceBean.getFarImage();
                    pile.setFarImage(far);
                } else {
                    pile.setFarImage("");
                }

                if (pointDeviceBean.getNearImage() != null && !pointDeviceBean.getNearImage().isEmpty()) {
                    String near = Constant.FILEHost + pointDeviceBean.getNearImage();
                    pile.setNearImage(near);
                } else {
                    pile.setNearImage("");
                }


                if (pointDeviceBean.getPoleImage() != null && !pointDeviceBean.getPoleImage().isEmpty()) {
                    String pole = Constant.FILEHost + pointDeviceBean.getPoleImage();
                    pile.setPoleImage(pole);
                } else {
                    pile.setPoleImage("");
                }

                if (pointDeviceBean.getPointModel() != null && pointDeviceBean.getPointType() == 1) {
                    List<TowerLibrary> towerLibrarys = daoSession.getTowerLibraryDao().queryBuilder()
                            .where(TowerLibraryDao.Properties.PoleModel.eq(pointDeviceBean.getPointModel())).list();
                    if (towerLibrarys.size() > 0) {
                        TowerLibrary towerLibrary = towerLibrarys.get(0);
                        if (towerLibrary != null || towerLibrary.getVoltageLevel() != null) {
                            String voltage = Pattern.compile(REGEX).matcher(towerLibrary.getVoltageLevel())
                                    .replaceAll("").trim();
                            if (Utils.isInteger(voltage)) {
                                pile.setPoleVoltage(Integer.parseInt(voltage));
                            } else {
                                pile.setPoleVoltage(0);
                            }
                        } else {
                            pile.setPoleVoltage(0);
                        }
                    } else {
                        pile.setPoleVoltage(0);
                    }
                } else {
                    pile.setPoleVoltage(0);
                }

                if (pointDeviceBean.getPointType() == 2) {
                    pile.setIsSettingFire(true);
                    pile.setSettingFireName(pointDeviceBean.getPointName());
                } else {
                    pile.setIsSettingFire(false);
                    pile.setSettingFireName("");
                }

                if (pointDeviceBean.getPointType() == 3) {
                    pile.setIsTB(true);
                    List<TransformerLibrary> transformerLibrarys = daoSession.getTransformerLibraryDao().queryBuilder()
                            .where(TransformerLibraryDao.Properties.PoleModel.eq(pile.getPoleCode())).list();
                    if (transformerLibrarys != null && transformerLibrarys.size() > 0) {
                        pile.setTbPoleCode(transformerLibrarys.get(0).getPoleModel());
                        pile.setPoleCode(transformerLibrarys.get(0).getTransformerModel());
                    }
                }

                if (pointDeviceBean.getPointType() == 6) {
                    pile.setIsCross(true);
                    CrossDeviceBean crossDeviceBean = daoSession.getCrossDeviceBeanDao()
                            .queryBuilder()
                            .where(CrossDeviceBeanDao.Properties.CrossUUID.eq(pile.getPileID())).unique();
                    String crossMark = crossInfo[crossDeviceBean.getCode()];
                    pile.setCrossMark(crossMark);
                } else {
                    pile.setIsCross(false);
                    pile.setCrossMark("");
                }


                piles.add(pile);
            }
            for (PolylineDeviceBean polylineDeviceBean : polylineDeviceBeans) {
                Wire wire = new Wire();
                wire.setFrontPole(polylineDeviceBean.getStartPointUUID());
                wire.setNextPole(polylineDeviceBean.getEndPointUUID());
                wire.setWireType(polylineDeviceBean.getPolylineModel());
                List<WireLibrary> wireLibrarys = daoSession.getWireLibraryDao().queryBuilder()
                        .where(WireLibraryDao.Properties.WireModel.eq(polylineDeviceBean.getPolylineModel()))
                        .list();
                if (wireLibrarys.size() > 0) {
                    WireLibrary wireLibrary = wireLibrarys.get(0);
                    if (wireLibrary != null) {
                        String voltage = Pattern.compile(REGEX).matcher(wireLibrary.getVoltageLevel())
                                .replaceAll("").trim();
                        if (Utils.isInteger(voltage)) {
                            wire.setWireVoltage(Integer.parseInt(voltage));
                        } else {
                            wire.setWireVoltage(0);
                        }
                    }
                }
                wires.add(wire);
            }
            projectSubmitToReviewPlatform.setPiles(piles);
            projectSubmitToReviewPlatform.setWires(wires);
            String json = JSONObject.toJSONString(projectSubmitToReviewPlatform);
            projectSubmitToReviewPlatform = JSONObject.parseObject(json, ProjectSubmitToReviewPlatform.class);
            System.out.println(json);
            json = json.replace(" ", "");
//            json = json.replaceAll("\\\\n\\\\r","");
            json = json.replace("\n", "");
            json = json.replace("\t", "");
            json = json.replace("\r", "");

            projectSubmitToReviewPlatform = JSONObject.parseObject(json, ProjectSubmitToReviewPlatform.class);

            String projectId = projectBean.getProjectId();
//            String projectId = "40289fb873b835130173b88b51b20028";
//            String loginName = "sjdw";
            String loginName = UserInfo.getInstance().userName;
            ProjectSubmitToReviewDto submitToReviewDto = new ProjectSubmitToReviewDto();
            submitToReviewDto.setProjectId(projectId);
            submitToReviewDto.setLoginName(loginName);
            submitToReviewDto.setProjectJsonStr(projectSubmitToReviewPlatform);
            json = JSONObject.toJSONString(submitToReviewDto);
            gTaskModel.submitToReview(submitToReviewDto);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void getPolylines(String projectId) {
        if (cspgProgressBar == null) {
            cspgProgressBar = CSPGProgressBar.show(activity);
        } else {
            cspgProgressBar.show();
        }
        try {
            gTaskModel.getPolylineDeviceByProjectId(projectId);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void getFailure(String msg) {

        if (null != cspgProgressBar && cspgProgressBar.isShowing()) {
            cspgProgressBar.dismiss();
        }
        ToastUtils.toast(activity, msg);
    }

    public void getTokenExpireFailure() {

        if (null != cspgProgressBar && cspgProgressBar.isShowing()) {
            cspgProgressBar.dismiss();
        }
        Intent intent = new Intent();
        intent.setClass(activity, LoginActivity.class);
        activity.startActivity(intent);
    }

    public void requestSuccess(ProjectDto projectDto) {
        if (projectDto != null) {
            processData(projectDto);
        }
    }

    public void requestSuccessPoints(List<PointDeviceDto> pointDeviceDtoList, int type) {
        if (pointDeviceDtoList != null) {
            processDataPoints(pointDeviceDtoList, type);
        }
    }

    public void requestSuccessPolylines(List<PolylineDeviceDto> polylineDeviceDtoLis, int type) {
        if (polylineDeviceDtoLis != null) {
            processDataPolylines(polylineDeviceDtoLis, type);
        }
    }

    public void deleteSuccessPoints(String projectId) {
        if (projectId != null) {
            deleteDesignPointData(projectId);
        }
    }

    public void deleteSuccessPolylines(String projectId) {
        if (projectId != null) {
            deleteDesignPolylineData(projectId);
        }
    }

    public void updateSuccess() {
        ProjectDto projectDto = projectModeConverterFactoryToDto(this.projectBean);
        if (projectDto != null) {
            processData(projectDto);
        }
    }

    //清空设计数据
    private void deleteDesignPointData(String projectId) {
        List<PointDeviceBean> pointDeviceBeanList = daoSession.getPointDeviceBeanDao().queryBuilder().where(PointDeviceBeanDao.Properties.ProjectId.eq(projectId)).list();
        daoSession.getPointDeviceBeanDao().rx()
                .deleteInTx(pointDeviceBeanList.toArray(new PointDeviceBean[pointDeviceBeanList.size()]))
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Action1<Void>() {
                    @Override
                    public void call(Void aVoid) {
                        if (null != cspgProgressBar && cspgProgressBar.isShowing()) {
                            cspgProgressBar.dismiss();
                        }
                        Toast.makeText(activity, "点设备数据删除完成", Toast.LENGTH_LONG).show();
                    }
                });
        daoSession.getCrossDeviceBeanDao()
                .queryBuilder()
                .where(CrossDeviceBeanDao.Properties.ProjectId.eq(projectId))
                .rx()
                .list()
                .subscribe(new Action1<List<CrossDeviceBean>>() {
                    @Override
                    public void call(List<CrossDeviceBean> crossDeviceBeans) {
                        daoSession.getCrossDeviceBeanDao().deleteInTx(crossDeviceBeans);
                    }
                });
    }

    //清空设计数据
    private void deleteDesignPolylineData(String projectId) {
        List<PolylineDeviceBean> polylineDeviceBeanList = daoSession.getPolylineDeviceBeanDao().queryBuilder().where(PolylineDeviceBeanDao.Properties.ProjectId.eq(projectId)).list();
        daoSession.getPolylineDeviceBeanDao().rx()
                .deleteInTx(polylineDeviceBeanList.toArray(new PolylineDeviceBean[polylineDeviceBeanList.size()]))
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Action1<Void>() {
                    @Override
                    public void call(Void aVoid) {
                        if (null != cspgProgressBar && cspgProgressBar.isShowing()) {
                            cspgProgressBar.dismiss();
                        }
                        Toast.makeText(activity, "导线数据删除完成", Toast.LENGTH_LONG).show();
                    }
                });
    }

    @Override
    public void netWorkError(String netError) {
//        activity.hideProgress();
//        activity.toast(netError);

        if (null != cspgProgressBar && cspgProgressBar.isShowing()) {
            cspgProgressBar.dismiss();
        }
        ToastUtils.toast(activity, netError);
        if (activity instanceof MainActivity) {
            //activity.openNewActivity(LoginActivity.class);
            Intent intent = new Intent();
            intent.setClass(activity, LoginActivity.class);
            activity.startActivity(intent);
        }
    }

    @Override
    public void httpRequestFailure(String noDataError) {
//        activity.hideProgress();
////        activity.toast(noDataError);
        if (null != cspgProgressBar && cspgProgressBar.isShowing()) {
            cspgProgressBar.dismiss();
        }
        ToastUtils.toast(activity, noDataError);
        if (activity instanceof MainActivity) {
            //activity.openNewActivity(LoginActivity.class);
            Intent intent = new Intent();
            intent.setClass(activity, LoginActivity.class);
            activity.startActivity(intent);
        }
    }

    @Override
    public void httpRequestSuccess() {
        if (null != cspgProgressBar && cspgProgressBar.isShowing()) {
            cspgProgressBar.dismiss();
        }
    }

    public void submitToReviewSuccess() {
        try {
            gTaskModel.updateProject(projectModeConverterFactoryToDto(projectBean));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void processData(ProjectDto projectDto) {
        if (type == 1) //更新项目状态
        {
            updateProjectStatus(this.index, projectModeConverterFactoryToBean(projectDto));
        } else if (type == 2) //更新本地方案名称
        {

            saveScheme(this.index, projectModeConverterFactoryToBean(projectDto), projectDto.getSchemeName(), projectDto.getSchemaType());
        } else if (type == 3) {
            if (null != cspgProgressBar && cspgProgressBar.isShowing()) {
                cspgProgressBar.dismiss();
            }
            daoSession.getProjectBeanDao().update(projectBean);
            ToastUtils.toast(this.activity, "工程信息更新成功。。。。。");
        } else if (type == 4) {
            updateProjectStatus(this.index, projectModeConverterFactoryToBean(projectDto));
        }
    }

    // type : 0  设备上传 1 设备按项目下载
    private void processDataPoints(List<PointDeviceDto> pointDeviceDtos, int type) {
        if (type == 0) {
            if (pointDeviceDtos.size() == this.pointDeviceBeanList.size()) {
                Toast.makeText(activity, "点设备上传成功。。。", Toast.LENGTH_SHORT).show();
//            ToastUtils.toast(activity, "点设备上传成功。。。");
                uploadPolylines(this.polylineDeviceBeanList);
            } else {
                gTaskModel.uploadAllPoint(pointDeviceBeansConverterFactoryToDtos(pointDeviceBeanList));
            }
        } else if (type == 1) {
            if (pointDeviceDtos.size() > 0) {
                List<PointDeviceBean> list = daoSession.getPointDeviceBeanDao().queryBuilder()
                        .where(PointDeviceBeanDao.Properties.ProjectId.eq(pointDeviceDtos.get(0).getProjectId())).list();
                if (list.size() > 0) {
                    daoSession.getPointDeviceBeanDao().deleteInTx(list);
                }
                try {
                    daoSession.getPointDeviceBeanDao().insertOrReplaceInTx(pointDeviceDtosConverterFactoryToBeans(pointDeviceDtos));
                } catch (Exception e) {
                    Log.e("point", "点存入数据库失败");
                }
//               daoSession.getPointDeviceBeanDao().insertInTx(pointDeviceDtosConverterFactoryToBeans(pointDeviceDtos));
//                daoSession.getPointDeviceBeanDao().rx().deleteAll().subscribe(new Action1<Void>() {
//                    @Override
//                    public void call(Void aVoid) {
//
//                        daoSession.getPointDeviceBeanDao().rx()
//                                .insertInTx(pointDeviceDtosConverterFactoryToBeans(pointDeviceDtos))
//                                .subscribe();
//                    }
//                });
            }

        }
        if (null != cspgProgressBar && cspgProgressBar.isShowing()) {
            cspgProgressBar.dismiss();
        }
    }

    // type : 0  设备上传 1 设备按项目下载
    private void processDataPolylines(List<PolylineDeviceDto> polylineDeviceDtos, int type) {
//        if (null != cspgProgressBar && cspgProgressBar.isShowing()) {
//            cspgProgressBar.dismiss();
//        }
        if (type == 0) {
            if (polylineDeviceDtos.size() == this.polylineDeviceBeanList.size()) {
                ToastUtils.toast(activity, "导线上传成功。。。");
                updateProject(projectBean, 1, index);
            } else {
                uploadPolylines(this.polylineDeviceBeanList);
            }
        } else if (type == 1) {
            if (polylineDeviceDtos.size() > 0) {
                PolylineDeviceDto polylineDeviceDto = polylineDeviceDtos.get(0);
                List<PolylineDeviceBean> list = daoSession.getPolylineDeviceBeanDao().queryBuilder()
                        .where(PolylineDeviceBeanDao.Properties.ProjectId.eq(polylineDeviceDto.getProjectId())).list();
                if (list.size() > 0) {
                    daoSession.getPolylineDeviceBeanDao().deleteInTx(list);
                }
                try {
//                daoSession.getPolylineDeviceBeanDao()
//                                .saveInTx(polylineDeviceDtosConverterFactoryToBeans(polylineDeviceDtos));
                    daoSession.getPolylineDeviceBeanDao().insertOrReplaceInTx(polylineDeviceDtosConverterFactoryToBeans(polylineDeviceDtos));
                } catch (Exception e) {
                    Log.e("polyline", "线存入数据库失败");
                }
//                daoSession.getPolylineDeviceBeanDao().rx().deleteAll().subscribe(new Action1<Void>() {
//                    @Override
//                    public void call(Void aVoid) {
//                        daoSession.getPolylineDeviceBeanDao().rx()
//                                .insertInTx(polylineDeviceDtosConverterFactoryToBeans(polylineDeviceDtos))
//                                .subscribe();
//                    }
//                });
            }
        }
        if (null != cspgProgressBar && cspgProgressBar.isShowing()) {
            cspgProgressBar.dismiss();
        }
    }

    //更新项目中的方案名称
    private void saveScheme(int index, ProjectBean projectBean, String schemeName, String schemeType) {
        projectBean.setSchemeName(schemeName);
        projectBean.setSchemaType(schemeType);
        daoSession.getProjectBeanDao().rx().save(projectBean)
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(
                        projectBean1 -> {
                            projectBeanList.set(index, projectBean1);
//                            projectBeanList.remove(index);
//                            projectBeanList.add(index,projectBean1);
                            refreshListView();
                            Toast.makeText(activity, "修改成功......", Toast.LENGTH_LONG).show();
                            if (null != cspgProgressBar && cspgProgressBar.isShowing()) {
                                cspgProgressBar.dismiss();
                            }
                        }
                );
    }

    //修改项目状态为完成
    private void updateProjectStatus(int index, ProjectBean projectBean) {
        daoSession.getProjectBeanDao().rx().save(projectBean).observeOn(AndroidSchedulers.mainThread()).subscribe(pb -> {
                    if (!projectBean.getProjectStatus().equals("doing") && projectBeanList.size() > index) {
                        projectBeanList.remove(index);
                    }
                    if (projectBeanList.size() > index && UserInfo.getInstance().role.contains("设计")
                            && projectBean.getProjectStatus().equals("doing")
                    ) {
                        projectBeanList.remove(index);
                    }
                    refreshListView();
                    if (this.type == 4) {
                        ToastUtils.toast(activity, "数据上传成功！！！");
                    } else {
                        Toast.makeText(activity, "项目状态已经更新", Toast.LENGTH_LONG).show();
                    }
                    if (null != cspgProgressBar && cspgProgressBar.isShowing()) {
                        cspgProgressBar.dismiss();
                    }
                }
        );
    }

    private void refreshListView() {
        dataList.clear();
        for (int i = 0; i < projectBeanList.size(); i++) {
            HashMap<String, String> hashMap = new HashMap<String, String>();
            hashMap.put("title", projectBeanList.get(i).getProjectTitle());
            hashMap.put("name", projectBeanList.get(i).getProjectName());
            if (projectBeanList.get(i).getProjectStatus().equals("doing")) {
                hashMap.put("status", "设计中");
            } else if (projectBeanList.get(i).getProjectStatus().equals("did")) {
                hashMap.put("status", "完成");
            } else if (projectBeanList.get(i).getProjectStatus().equals("done")) {
                hashMap.put("status", "待审核");
            } else if (projectBeanList.get(i).getProjectStatus().equals("checked")) {
                hashMap.put("status", "审核通过");
            }
            dataList.add(hashMap);

        }
        adapter.notifyDataSetChanged();
    }


    private List<ProjectBean> projectModesConverterFactory(List<ProjectDto> projectDtoList) {
        List<ProjectBean> projectBeanList = new ArrayList<>();
        for (int i = 0; i < projectDtoList.size(); i++) {
            ProjectDto projectDto = projectDtoList.get(i);
//            if (projectDto.getUserName().equals(UserInfo.getInstance().userName))
//            {
            ProjectBean projectBean = new ProjectBean();
            projectBean.setId(projectDto.getId());
            projectBean.setUserName(projectDto.getUserName());
            projectBean.setProjectTitle(projectDto.getProjectTitle());
            projectBean.setProjectId(projectDto.getProjectId());
            projectBean.setProjectStatus(projectDto.getProjectStatus());
            projectBean.setProjectName(projectDto.getProjectName());
            projectBean.setSchemeName(projectDto.getSchemeName());
            projectBean.setSchemaType(projectDto.getSchemaType());
            projectBeanList.add(projectBean);
//            }
        }
        return projectBeanList;
    }

    private ProjectBean projectModeConverterFactoryToBean(ProjectDto projectDto) {
        ProjectBean projectBean = new ProjectBean();
        projectBean.setId(projectDto.getId());
        projectBean.setUserName(projectDto.getUserName());
        projectBean.setProjectTitle(projectDto.getProjectTitle());
        projectBean.setProjectId(projectDto.getProjectId());
        projectBean.setProjectStatus(projectDto.getProjectStatus());
        projectBean.setProjectName(projectDto.getProjectName());
        projectBean.setSchemeName(projectDto.getSchemeName());
        projectBean.setSchemaType(projectDto.getSchemaType());
        projectBean.setAffiliattedUnit(projectDto.getAffiliattedUnit());
        projectBean.setProjectCode(projectDto.getProjectCode());
        projectBean.setProjectInvestment(projectDto.getProjectInvestment());
        projectBean.setProjectDate(projectDto.getProjectDate());
        projectBean.setVoltageLevel(projectDto.getVoltageLevel());
        projectBean.setCarDistance(projectDto.getCarDistance());
        projectBean.setHandDistance(projectDto.getHandDistance());
        projectBean.setRemark(projectDto.getRemark());
//        projectBeanList.add(projectBean);
        return projectBean;
    }

    private ProjectDto projectModeConverterFactoryToDto(ProjectBean projectBean) {
        ProjectDto projectDto = new ProjectDto();
        projectDto.setId(projectBean.getId());
        projectDto.setUserName(projectBean.getUserName());
        projectDto.setProjectTitle(projectBean.getProjectTitle());
        projectDto.setProjectId(projectBean.getProjectId());
        projectDto.setProjectStatus(projectBean.getProjectStatus());
        projectDto.setProjectName(projectBean.getProjectName());
        projectDto.setSchemeName(projectBean.getSchemeName());
        projectDto.setSchemaType(projectBean.getSchemaType());
        projectDto.setAffiliattedUnit(projectBean.getAffiliattedUnit());
        projectDto.setProjectCode(projectBean.getProjectCode());
        projectDto.setProjectInvestment(projectBean.getProjectInvestment());
        projectDto.setProjectDate(projectBean.getProjectDate());
        projectDto.setVoltageLevel(projectBean.getVoltageLevel());
        projectDto.setCarDistance(projectBean.getCarDistance());
        projectDto.setHandDistance(projectBean.getHandDistance());
        projectDto.setRemark(projectBean.getRemark());
        return projectDto;
    }

    private List<PointDeviceBean> pointDeviceDtosConverterFactoryToBeans(List<PointDeviceDto> pointDeviceDtos) {
        List<PointDeviceBean> pointDeviceBeans = new ArrayList<>();
        for (int i = 0; i < pointDeviceDtos.size(); i++) {
            pointDeviceBeans.add(pointDeviceDtoConverterFactoryToBean(pointDeviceDtos.get(i)));
        }
        return pointDeviceBeans;
    }


    private PointDeviceBean pointDeviceDtoConverterFactoryToBean(PointDeviceDto pointDeviceDto) {
        PointDeviceBean pointDeviceBean = new PointDeviceBean();
        pointDeviceBean.setPointId(pointDeviceDto.getId());
        pointDeviceBean.setProjectId(pointDeviceDto.getProjectId());
        pointDeviceBean.setPointName(pointDeviceDto.getPointName());
        pointDeviceBean.setPointType(pointDeviceDto.getPointType());
        pointDeviceBean.setPointUuid(pointDeviceDto.getPointUuid());
        pointDeviceBean.setPointModel(pointDeviceDto.getPointModel());
        pointDeviceBean.setLatitude(pointDeviceDto.getLatitude());
        pointDeviceBean.setLongitude(pointDeviceDto.getLongitude());
        pointDeviceBean.setPrePointUUID(pointDeviceDto.getPrePointUuid());
        pointDeviceBean.setPointStatue(pointDeviceDto.getPointStatue());
        pointDeviceBean.setSchemaName(pointDeviceDto.getSchemaName());
        pointDeviceBean.setDistance(pointDeviceDto.getDistance());
        pointDeviceBean.setFarImage(pointDeviceDto.getFarImage());
        pointDeviceBean.setNearImage(pointDeviceDto.getNearImage());
        pointDeviceBean.setPoleImage(pointDeviceDto.getPoleImage());
        if (pointDeviceDto.getCrossMark() != null && Utils.isNumber(pointDeviceDto.getCrossMark())) {
            int cross = Integer.parseInt(pointDeviceDto.getCrossMark());
            CrossDeviceBean crossDeviceBean = new CrossDeviceBean();
            crossDeviceBean.setProjectId(pointDeviceDto.getProjectId());
            crossDeviceBean.setCrossUUID(pointDeviceDto.getPointUuid());
            crossDeviceBean.setCode(cross);
            daoSession.getCrossDeviceBeanDao().insertOrReplace(crossDeviceBean);
        }
        return pointDeviceBean;
    }

    private List<PointDeviceDto> pointDeviceBeansConverterFactoryToDtos(List<PointDeviceBean> pointDeviceBeans) {
        List<PointDeviceDto> pointDeviceDtos = new ArrayList<>();
        for (int i = 0; i < pointDeviceBeans.size(); i++) {
            pointDeviceDtos.add(pointDeviceBeanConverterFactoryToDto(pointDeviceBeans.get(i)));
        }
        return pointDeviceDtos;
    }

    private PointDeviceDto pointDeviceBeanConverterFactoryToDto(PointDeviceBean pointDeviceBean) {
        PointDeviceDto pointDeviceDto = new PointDeviceDto();
//        pointDeviceDto.setId( pointDeviceBean.getPointId());
        pointDeviceDto.setPointId(pointDeviceBean.getPointId());
        pointDeviceDto.setProjectId(pointDeviceBean.getProjectId());
        pointDeviceDto.setPointName(pointDeviceBean.getPointName());
        pointDeviceDto.setPointType(pointDeviceBean.getPointType());
        pointDeviceDto.setPointUuid(pointDeviceBean.getPointUuid());
        pointDeviceDto.setPointModel(pointDeviceBean.getPointModel());
        pointDeviceDto.setLatitude(pointDeviceBean.getLatitude());
        pointDeviceDto.setLongitude(pointDeviceBean.getLongitude());
        pointDeviceDto.setPrePointUuid(pointDeviceBean.getPrePointUUID());
        pointDeviceDto.setPointStatue(pointDeviceBean.getPointStatue());
        pointDeviceDto.setSchemaName(pointDeviceBean.getSchemaName());
        pointDeviceDto.setDistance(pointDeviceBean.getDistance());
        pointDeviceDto.setFarImage(pointDeviceBean.getFarImage());
        pointDeviceDto.setNearImage(pointDeviceBean.getNearImage());
        pointDeviceDto.setPoleImage(pointDeviceBean.getPoleImage());
        CrossDeviceBean crossDeviceBean = daoSession.getCrossDeviceBeanDao().queryBuilder().where(CrossDeviceBeanDao.Properties.CrossUUID.eq(pointDeviceBean.getPointUuid()))
                .unique();
        if (crossDeviceBean != null) {
            pointDeviceDto.setCrossMark(crossDeviceBean.getCode() + "");
        }
        return pointDeviceDto;
    }

    private List<PolylineDeviceBean> polylineDeviceDtosConverterFactoryToBeans(List<PolylineDeviceDto> polylineDeviceDtos) {
        List<PolylineDeviceBean> polylineDeviceBeans = new ArrayList<>();
        for (int i = 0; i < polylineDeviceDtos.size(); i++) {
            polylineDeviceBeans.add(polylineDeviceDtoConverterFactoryToBean(polylineDeviceDtos.get(i)));
        }
        return polylineDeviceBeans;
    }


    private PolylineDeviceBean polylineDeviceDtoConverterFactoryToBean(PolylineDeviceDto polylineDeviceDto) {
        PolylineDeviceBean polylineDeviceBean = new PolylineDeviceBean();

        polylineDeviceBean.setPolyLineId(polylineDeviceDto.getId());
        polylineDeviceBean.setProjectId(polylineDeviceDto.getProjectId());
        polylineDeviceBean.setStartPointUUID(polylineDeviceDto.getStartPointUUID());
        polylineDeviceBean.setEndPointUUID(polylineDeviceDto.getEndPointUUID());
        polylineDeviceBean.setStartLatitude(polylineDeviceDto.getStartLatitude());
        polylineDeviceBean.setStartLongitude(polylineDeviceDto.getStartLongitude());
        polylineDeviceBean.setEndLatitude(polylineDeviceDto.getEndLatitude());
        polylineDeviceBean.setEndLongitude(polylineDeviceDto.getEndLongitude());
        polylineDeviceBean.setPolylineUuid(polylineDeviceDto.getPolylineUuid());
        polylineDeviceBean.setPolylineModel(polylineDeviceDto.getPolylineModel());
        polylineDeviceBean.setStartPointName(polylineDeviceDto.getStartPointName());
        polylineDeviceBean.setEndPointName(polylineDeviceDto.getEndPointName());
        polylineDeviceBean.setCircuitsNum(polylineDeviceDto.getCircuitsNum());
        polylineDeviceBean.setMargin(polylineDeviceDto.getMargin());
        return polylineDeviceBean;
    }

    private List<PolylineDeviceDto> polylineDeviceBeansConverterFactoryToDtos(List<PolylineDeviceBean> polylineDeviceBeans) {
        List<PolylineDeviceDto> polylineDeviceDtos = new ArrayList<>();
        for (int i = 0; i < polylineDeviceBeans.size(); i++) {
            polylineDeviceDtos.add(polylineDeviceBeanConverterFactoryToDto(polylineDeviceBeans.get(i)));
        }
        return polylineDeviceDtos;
    }

    private PolylineDeviceDto polylineDeviceBeanConverterFactoryToDto(PolylineDeviceBean polylineDeviceBean) {
        PolylineDeviceDto polylineDeviceDto = new PolylineDeviceDto();

        polylineDeviceDto.setId(polylineDeviceBean.getPolyLineId());
        polylineDeviceDto.setProjectId(polylineDeviceBean.getProjectId());
        polylineDeviceDto.setStartPointUUID(polylineDeviceBean.getStartPointUUID());
        polylineDeviceDto.setEndPointUUID(polylineDeviceBean.getEndPointUUID());
        polylineDeviceDto.setStartLatitude(polylineDeviceBean.getStartLatitude());
        polylineDeviceDto.setStartLongitude(polylineDeviceBean.getStartLongitude());
        polylineDeviceDto.setEndLatitude(polylineDeviceBean.getEndLatitude());
        polylineDeviceDto.setEndLongitude(polylineDeviceBean.getEndLongitude());
        polylineDeviceDto.setPolylineUuid(polylineDeviceBean.getPolylineUuid());
        polylineDeviceDto.setPolylineModel(polylineDeviceBean.getPolylineModel());
        polylineDeviceDto.setStartPointName(polylineDeviceBean.getStartPointName());
        polylineDeviceDto.setEndPointName(polylineDeviceBean.getEndPointName());
        polylineDeviceDto.setCircuitsNum(polylineDeviceBean.getCircuitsNum());
        polylineDeviceDto.setMargin(polylineDeviceBean.getMargin());
        return polylineDeviceDto;
    }

    private Double costInvest(String projectId) {
        Double cost = 0D;
        daoSession.getPointDeviceBeanDao().queryBuilder().where(PointDeviceBeanDao.Properties.ProjectId.eq(projectId),
                PointDeviceBeanDao.Properties.PointType.eq(1)).rx()
                .list().observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Action1<List<PointDeviceBean>>() {
                    @Override
                    public void call(List<PointDeviceBean> pointDeviceBeans) {
                        List<String> models = new ArrayList<>();
                        for (int i = 0; i < pointDeviceBeans.size(); i++) {
                            String model = pointDeviceBeans.get(i).getPointModel();
                            if (!models.contains(model)) {
                                models.add(model);
                            }
                        }
                        for (int i = 0; i < models.size(); i++) {

                        }

                    }
                });
        List<PointDeviceBean> transformerBeans = daoSession.getPointDeviceBeanDao().queryBuilder().where(PointDeviceBeanDao.Properties.ProjectId.eq(projectId),
                PointDeviceBeanDao.Properties.PointType.eq(3))
                .list();
        if (transformerBeans != null) {
            int capacity = 0;
            List<String> models = new ArrayList<>();
            for (int i = 0; i < transformerBeans.size(); i++) {
                String model = transformerBeans.get(i).getPointModel();
                if (!models.contains(model)) {
                    models.add(model);
                }
                if (model == null || model.isEmpty()) {
                    continue;
                }
                List<TransformerLibrary> transformerLibrarys = daoSession.getTransformerLibraryDao().queryBuilder()
                        .where(TransformerLibraryDao.Properties.TransformerModel.eq(model)).list();
                if (transformerLibrarys.size() > 0) {
                    TransformerLibrary transformerLibrary = transformerLibrarys.get(0);
                    capacity += Integer.parseInt(transformerLibrary.getCapacity());
                    String transformerCost = transformerLibrary.getCost();
                    if (transformerCost != null) {
                        if (Utils.isDouble(transformerCost)) {
                            cost += Double.parseDouble(transformerCost);
                        } else if (Utils.isInteger(transformerCost)) {
                            cost += Integer.parseInt(transformerCost);
                        }
                    }
                }

            }
        }
        List<PolylineDeviceBean> polylineDeviceBeans = daoSession.getPolylineDeviceBeanDao()
                .queryBuilder().where(PolylineDeviceBeanDao.Properties.ProjectId.eq(projectId))
                .list();
        if (polylineDeviceBeans != null) {
            Double totalDistance = 0D;
            Map<String, Double> map = new HashMap<>();
            for (int i = 0; i < polylineDeviceBeans.size(); i++) {
                PolylineDeviceBean deviceBean = polylineDeviceBeans.get(i);
                Double distance = DistanceUtil.getDistance(
                        new LatLng(deviceBean.getStartLatitude(), deviceBean.getStartLongitude()),
                        new LatLng(deviceBean.getEndLatitude(), deviceBean.getEndLongitude()));
                distance = new BigDecimal(distance).setScale(2, RoundingMode.UP).doubleValue();
                totalDistance += distance;
                if (map.get(deviceBean.getPolylineModel()) == null) {
                    map.put(deviceBean.getPolylineModel(), distance);
                } else {
                    Double value = map.get(deviceBean.getPolylineModel());
                    value += distance;
                    map.put(deviceBean.getPolylineModel(), value);
                }
                List<WireLibrary> wireLibrarys = daoSession.getWireLibraryDao().queryBuilder()
                        .where(WireLibraryDao.Properties.WireModel.eq(deviceBean.getPolylineModel()))
                        .list();
                if (wireLibrarys.size() > 0) {
                    WireLibrary wireLibrary = wireLibrarys.get(0);
                    String polylineCost = wireLibrary.getCostPerKM();
                    if (polylineCost != null) {
                        if (Utils.isDouble(polylineCost)) {
                            cost += Double.parseDouble(polylineCost) * distance / 1000;
                        } else if (Utils.isInteger(polylineCost)) {
                            cost += Integer.parseInt(polylineCost) * distance / 1000;
                        }
                    }
                }
            }
            totalDistance = totalDistance / 1000;
            totalDistance = new BigDecimal(totalDistance).setScale(4, RoundingMode.UP).doubleValue();
            cost = new BigDecimal(cost).setScale(4, RoundingMode.UP).doubleValue();
        }
        return cost;
    }
}
